package top.deepdesigner.controller.systemManage;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.deepdesigner.pojo.DtsAdmin;
import top.deepdesigner.service.DtsAdminService;
import top.deepdesigner.util.ResponseUtil;
import top.deepdesigner.util.bcrypt.BCryptPasswordEncoder;

import java.util.HashMap;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/24 星期六 17:27:28 <br/>
 */
@RestController
@CrossOrigin
@RequestMapping("/admin/profile")
public class ProfileController {

  @Autowired
  private DtsAdminService adminService;

  @PostMapping("/password")
  public Object password(@RequestBody HashMap<String, Object> map) {
    String oldPassword = (String) map.get("oldPassword");
    String newPassword = (String) map.get("newPassword");
    String newPassword2 = (String) map.get("newPassword2");
    if (StringUtils.isEmpty(oldPassword)) return ResponseUtil.fail(700, "密码不能为空");
    if (StringUtils.isEmpty(newPassword)) return ResponseUtil.fail(700, "密码不能为空");
    if (StringUtils.isEmpty(newPassword2)) return ResponseUtil.fail(700, "密码不能为空");
    Subject subject = SecurityUtils.getSubject();
    DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    if (encoder.matches(oldPassword, admin.getPassword())) {
      adminService.updatePassword(admin.getId(), newPassword);
      return ResponseUtil.ok();
    }
    return ResponseUtil.fail(700, "密码更新失败");
  }
}
